var express = require('express');
var router = express.Router();
var {wss, tables, players, broadcast} = require('../wss');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/tables', (req, res) => {
  res.json({ tables });
});

router.post('/login', (req, res) => {
  const player = req.body.player;
  if (!player || !player.name) {
    return res.json({ error: '请输入玩家姓名' });
  }
  for (let i = 0; i < tables.length; i++) {
    const table = tables[i];
    if (!table.start) {
      const emptySeatIndex = table.seats.findIndex(player => !player);
      if (emptySeatIndex !== -1) {
        player.table = i;
        player.seat = emptySeatIndex;
        table.seats[emptySeatIndex] = player;
        players.push(player);
        if (table.seats.every(player => player)) {
          table.start = true;
        }
        // 通知所有客户端牌桌状态更新
        broadcast({ tables });
        return res.json({ tables });
      }
    }
  }
  res.json({ error: '没有可用座位，请稍后再试' });
});

router.post('/join', (req, res) => {
  const tableIndex = parseInt(req.body.table);
  const seatIndex = parseInt(req.body.seat);
  const player = players.find(item => item.name == req.body.player.name);
  if (!player) {
    return res.json({ error: '未找到该玩家' });
  }
  const table = tables[tableIndex];

  if (table.start) {
    return res.json({ error: '此桌游戏已开始，请选择其他桌' });
  }
  if (table.seats[seatIndex]) {
    return res.json({ error: '此座位已有人，请选择其他座位' });
  } 
  if (player.table != null && player.seat != null) {
    tables[player.table].seats[player.seat] = null;
  }
  player.table = tableIndex;
  player.seat = seatIndex;
  table.seats[seatIndex] = player;
  if (table.seats.every(player => player)) {
    table.start = true;
  }
  // 通知所有客户端牌桌状态更新
  broadcast({ tables });
  res.json({ tables });
});


module.exports = router;
